package com.fly.core.config;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 数据库配置信息加载类
 * 
 * @author 00fly
 * @version [版本号, 2021年10月24日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Configuration
public class SysDataBaseConfig
{
    @Autowired
    ConfigurableEnvironment environment;
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    private List<SysConfig> getAll()
    {
        return jdbcTemplate.query("SELECT `key`, `value`, `status` FROM sys_config WHERE `status` = '1'", new BeanPropertyRowMapper<>(SysConfig.class));
    }
    
    @PostConstruct
    public void initDatabasePropertySource()
    {
        try
        {
            Resource resource = new ClassPathResource("/sql/init.sql");
            String sqlText = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
            Arrays.stream(sqlText.split(";")).filter(StringUtils::isNotBlank).forEach(jdbcTemplate::execute);
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
        // 取配置信息列表并过滤空值
        Map<String, Object> collect = getAll().stream().filter(p -> StringUtils.isNoneEmpty(p.getKey(), p.getValue())).collect(Collectors.toMap(SysConfig::getKey, SysConfig::getValue));
        
        // 追加配置到系统变量中,name取值随意
        environment.getPropertySources().addLast(new MapPropertySource("sys_config", collect));
        log.info("sys_config data: {}", collect);
    }
}

/**
 * 
 * 配置信息实体对象
 * 
 * @author 00fly
 * @version [版本号, 2021年10月24日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Data
class SysConfig
{
    private String key;
    
    private String value;
    
    private String status;
}
